<template>
  <div class="page-controller">
    <FISearchForm
      v-show="showSearch"
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchFormId="tableId"
      :search-table-id="tableId"
      :searchNum="searchItemCount"
      :model="state.query"
      :showCollapse="false"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :showDynamicForm="true"
      @submit="searchFn"
      @deleteFilterItem="deleteFilterItem"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="seqTypeId" label="序列号编码">
          <FIInput v-model="state.query.seqTypeId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="remark" label="序列号名称">
          <FIInput v-model="state.query.remark" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="sequenceMaintTable"
      class="box-radius2"
      :id="`inqu_${tableId}`"
      :tableId="tableId"
      :readonly="false"
      title="序列号管理列表"
      :data="state.dataList"
      primaryKey="seqTypeId"
      v-model:columns="columns"
      :toolbarConfig="true"
      :isCanAddRow="true"
      :locked="isTableLocked"
      :isLoading="isTableLoading"
      checkMode="check"
      insertable
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @filter-reset="searchFn"
      @column-filter-confirm="filterConfirm"
      @change-sort="searchFn"
      @table-refresh="searchFn"
      @lock-toggle="isTableLocked = !isTableLocked"
      @search-toggle="showSearch = !showSearch"
      @selection-change="handleSelectionChange"
      @action-click="handleAction"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
    >
      <!-- <template #dateCycle="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.dateCycle"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.dateCycle }}</span>
      </template> -->
      <!-- <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认要生删除选中数据吗？"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template> -->
      <template #empty> 暂无数据 </template>
    </FITable>

    <assign-post
      :postShow="postShow"
      @update:postShow="(newValue) => (postShow = newValue)"
      :editData="selectedNode"
      @get-list="searchFn"
    ></assign-post>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import assignPost from './assignPost.vue'
import register from './register.vue'
// import OyTable from '@/components/OyTable/index.vue'
// import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { clientFilter } from '@/utils/common.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { apiQueryCodeitem } from '@/api/common'
import { apiGetCodeitems } from '@/api/configEnvMaint/index'
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLocked = ref(false)
const isTableLoading = ref(false)
const postShow = ref(false)
const sequenceMaintTable = ref(null)
// 页面编码
const tableId = 'sequenceMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const state = reactive({
  query: {
    remark: '',
    seqTypeId: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const dataArr = ref([])
const columns: Column = reactive([
  {
    label: '序列号编码',
    prop: 'seqTypeId',
    align: 'center',
    width: '180',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { seqTypeId: [{ required: true, message: '请输入序列号编码', trigger: 'blur' }] },
    },
  },
  {
    label: '序列号名称',
    prop: 'remark',
    align: 'center',
    width: '180',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { remark: [{ required: true, message: '请输入序列号名称', trigger: 'blur' }] },
    },
  },
  // {
  //   label: '账套',
  //   prop: 'accsetNo',
  //   align: 'center',
  //   width: '180',
  //   queryName: '',
  //   editable: true,
  //   // sortable: true,
  //   // filterable: true,
  //   modelValue: { inputValue: '' },
  //   editType: 'input',
  //   editConfig: {
  //     rules: { accsetNo: [{ required: true, message: '请输入账套', trigger: 'blur' }] },
  //   },
  // },

  {
    label: '是否连号',
    prop: 'isLinked',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        // { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
    },
    editConfig: {
      rules: { isLinked: [{ required: true, message: '请输入是否连号', trigger: 'blur' }] },
      options: [
        // { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },

  {
    label: '序列号分段数',
    prop: 'seqSubsecs',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '日期循环级别',
    prop: 'dateCycle',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    // configValueToLable: {
    //   list: [
    //     { value: 1, label: '是' },
    //     { value: 0, label: '否' },
    //   ],

    // },
    editConfig: {
      // rules: { dateCycle: [{ required: true, message: '请输入日期循环级别', trigger: 'blur' }] },
      options: dataArr,
      // codeOption: { codesetCode: 'iplat.ed.dateCycle' },
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '序列号长度',
    prop: 'seqLmt',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      // { id: 'delete', type: 'delete' },
      // { id: 'b5555', type: 'add' },
      { id: 'openSubsec', type: 'action_openSubsec' },
      { id: 'b5555', type: 'add' },
    ],
  },
])

const smallCode = () => {
  apiGetCodeitems({ codesetCode: 'iplat.ed.dateCycle' })
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        dataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        sequenceMaintTable.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'dateCycle') {
            v.editConfig.options = dataArr
          }
        })
      }
    })
    .catch((error: any) => {})
}
const selectedNode = ref({})
const handleAction = (item, rowData, butoninfo) => {
  if (!rowData.seqTypeId) {
    useMessage().warning('请先定义序列号!')
  } else {
    // console.log(  item, rowData,butoninfo)
    postShow.value = true
    selectedNode.value = rowData
  }
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
// 列自定义筛选事件
const filterConfirm = (e: any) => {
  let selectedProp = e.columnItem.prop
  Array.isArray(columns) &&
    columns.forEach((item: any) => {
      if (item?.prop == selectedProp) {
        item.modelValue = e.columnItem?.modelValue
        item.showHighSearch = true
      }
    })
  searchFn('dynamic')
}
const deleteFilterItem = (e: any) => {
  let selectedProp = e
  Array.isArray(columns) &&
    columns.forEach((item: any) => {
      if (item?.prop == selectedProp) {
        item.modelValue = null
        item.showHighSearch = false
      }
    })
  searchFn()
}
const selectedTableList = ref([])
const handleSelectionChange = (e) => {
  console.log(e)
  selectedTableList.value = e
}

// 常规搜索条件个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  if (type == 'sort') {
    if (columns.length === columnsVal.length) {
      for (let i = 0; i < columns.length; i++) {
        columns[i].sortValue = columnsVal[i].sortValue
      }
    }
  }
  // 缓存筛选条件 --筛选条件包括常规筛选内容，还有动态的筛选内容 dynamicParams，排序orderbyParams等等内容
  const userData = LocalCache.getCache('user')
  const userId = userData.userId
  LocalCache.setCache(`${userId}-${tableId}-searchFormId`, state.query)
  // table锁定时客户端筛选 queryData根据具体页面数据赋值
  if (isTableLocked.value && type === 'dynamic') {
    state.dataList = clientFilter(state.query, state.dataList)
  } else {
    state.query.dynamicParams = []
    state.query.orderbyParams = []
    Array.isArray(columns) &&
      columns.forEach((item: any) => {
        // 排序
        if (item.sortable && item.sortValue) {
          const orderObj = {
            name: item.prop,
            queryName: item.queryName || item.prop,
            ops: item.sortValue,
          }
          state.query.orderbyParams.push(orderObj)
        }
        // 筛选
        if (item.showHighSearch === true) {
          if (item.editType === 'input') {
            const dynamicItem = {
              name: item.prop,
              queryName: 'tedfa00.form_Cname',
              ops: 'like',
              val: [item.modelValue?.inputValue || ''],
            }
            // 空
            if (item.modelValue?.isBlank) {
              dynamicItem.ops = 'isBlank'
              state.query.dynamicParams.push(dynamicItem)
            }
            // 非空
            if (item.modelValue?.notBlank) {
              dynamicItem.ops = 'notBlank'
              state.query.dynamicParams.push(dynamicItem)
            }

            if (!item.modelValue?.notBlank && !item.modelValue?.isBlank && item.modelValue?.inputValue) {
              state.query.dynamicParams.push(dynamicItem)
            }
          }
        }
      })
    isTableLoading.value = true
    apiRequestPost('/rm2/sequenceMaint/querySeqDef', {
      ...state.query,
      size: pageConfig.pageSize,
      current: pageConfig.currentPage,
    })
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
}
const handleModify = (obj, type = 'modify') => {
  const changeList = type === 'add' ? obj : [obj.action]
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/sequenceMaint/saveSeqDef', changeList)
    .then((res) => {
      isTableLoading.value = false
      // state.dataList = res.data.data.result
      if (res.data.success) {
        saveSuccessful.value = true
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const deleteRow = () => {
  console.log(selectedTableList.value)
  if (!selectedTableList.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(selectedTableList.value) &&
    selectedTableList.value.forEach((item: any) => {
      if (item?.seqTypeId) ids.push(item?.seqTypeId)
    })
  isTableLoading.value = true
  apiRequestPost('/rm2/sequenceMaint/deleteSeqDef', ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleModify(data, 'add')
}
const arr2 = ref([])
const getProjectname = () => {
  apiQueryCodeitem({ codesetCode: 'iplat.ed.dateCycle' }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data.result) &&
        res.data.data.result.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.itemCode}] ${item.itemCname}`
          item.value = item.itemCode
        })
      if (Array.isArray(res.data.data.result)) {
        const newArray = res.data.data.result.map((item) => ({
          label: `[${item.itemCode}] ${item.itemCname}`,
          value: item.itemCode,
        }))
        arr2.value = newArray
      }
    }
  })
}
onMounted(() => {
  smallCode()
  getProjectname()
  // 获取查询条件缓存
  const userData = LocalCache.getCache('user')
  const userId = userData.userId
  state.query = LocalCache.getCache(`${userId}-${tableId}-searchFormId`)
    ? LocalCache.getCache(`${userId}-${tableId}-searchFormId`)
    : state.query
  searchFn()
})
</script>
<style lang="less" scoped></style>
